#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>

#define BUFFER_SIZE 255

int main(int argc, char **argv) {
	if (argc < 4) {
		fprintf(stderr, "Not enough arguments: <server_ip> <message> <port> \n");
		return 1;
	}	

	int socket_handle;
	struct sockaddr_in echo_server;
	struct sockaddr_in echo_client;
	char buffer[BUFFER_SIZE];
	unsigned int echo_length, client_length;
	int received = 0;


	if ((socket_handle = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
		fprintf(stderr, "Couldn't create socket.\n");
		return 1;
	}

	memset(&echo_server, 0, sizeof(echo_server));
	echo_server.sin_family = AF_INET;
	echo_server.sin_addr.s_addr = inet_addr(argv[1]);
	echo_server.sin_port = htons(atoi(argv[3]));

	echo_length = strlen(argv[2]);
	if (sendto(socket_handle, argv[2], echo_length, 0, (struct sockaddr *) &echo_server, sizeof(echo_server)) != echo_length) {
		fprintf(stderr, "Wrong number of sent bytes.\n");
		return 1;
	}

	fprintf(stdout, "Received: ");
	client_length = sizeof(echo_client);
	if ((received = recvfrom(socket_handle, buffer, BUFFER_SIZE, 0, (struct sockaddr *) &echo_client, &client_length)) != echo_length) {
		fprintf(stderr, "Wrong number of received bytes.\n");
		return 1;
	}

	if (echo_server.sin_addr.s_addr != echo_client.sin_addr.s_addr) {
		fprintf(stderr, "Received a packet from an unexpected server.\n");
		return 1;
	}

	buffer[received] = '\0';
	printf("%s", buffer);
	printf("\n");
	close(socket_handle);
	return 0;
}
